package com.tian.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

/**
 * {@code @description:} 自定义需要继承Netty提供的SimpleChannelInboundHandler
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-05-14 9:10
 * {@code @version:} 1.0
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取数据
     *
     * @param channelHandlerContext 包含 管道pipeline和channel
     * @param msg                   客户端发送的数据，这里是以Object类型
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        System.out.println("Received message: " + msg);
        //将msg转成一个 ByteBuf,
        //ByteBuf是netty提供的
        ByteBuf msgObject = (ByteBuf) msg;
        System.out.println("收到客户端的消息是：" + msgObject.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址：" + channelHandlerContext.channel().remoteAddress());
    }

    /**
     * 数据读取完毕
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将数据写入到缓存，并刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端", StandardCharsets.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //遇到异常关闭
        ctx.close();
    }
}
